﻿/**
 * Copyright (C) 2011 original author and authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NGuice.Inject.Internal
{
    /// <summary>
    /// 不持有强类型的引用的key的最小集合
    /// </summary>
    internal sealed class WeakKeySet
    {
        /// <summary>
        /// 存储字符串而不引用强类型
        /// </summary>
        private ISet<string> backingSet;

        public bool Add<T>(Key<T> key)
        {
            if (backingSet == null)
            {
                backingSet = new HashSet<string>();
            }
            return backingSet.Add(key.ToString());
        }

        public bool Contains(object o)
        {
            // avoid calling key.toString() if the backing set is empty. toString is expensive in aggregate,
            // and most WeakKeySets are empty in practice (because they're used by top-level injectors)
            return backingSet != null && o.GetType() == typeof(Key<>) && backingSet.Contains(o.ToString());
        }
    }
}
